'use strict';

var pc = null;
var dataChannel = null;
var local = {
	stream:null,
	src:null
}

var remote = {
	stream:null,
	src:null
}

var remoteVideoTest = [];

var pcConfig = {
	'iceServers':[{
		'url':'stun:stun.l.google.com:19302'
	}]
}

var sdpConstraints = {
	'mandatory':{
		'OfferToReceiveAudio':true,
		'OfferToReceiveVideo':true
	}
}

var receiveChannel = null;

var server = null;
var pcConstraint = null;
var isChannelReady = false;
var dataConstraint = null;

/**
 * 初始化本地媒体资源
 */
function initialize(){
	let initialize = new Promise(
		function(resolve, reject){
			navigator.mediaDevices.getUserMedia({
				audio:true,
				video:true
			}).then(
				function(stream){
					console.log("initialize",stream);
					local.src = window.URL.createObjectURL(stream);
					local.stream = stream;
					createPeerConnectionAndDataChannel();
					resolve(local.src);
				},function(err){
					reject(err);
			}).catch(function(e){
				console.log("获取媒体资源时出错",e);
			});
		}
	);
	return initialize;
}  

function createPeerConnectionAndDataChannel(){
	
	pc = new RTCPeerConnection(pcConfig);
	pc.onicecandidate = handleIceCandidate;
	pc.onicecandidatestatechange = onIceStateChange;
	pc.onaddstream = handleRemoteStreamAdded;
	pc.onremovestream = handleRemoteStreamRemoved;
	pc.ondatachannel = receivehandler;
	
	dataChannel = pc.createDataChannel("dataChannel",dataConstraint);
	dataChannel.onopen = onSendChannelStateChange;
	dataChannel.onclose = onSendChannelStateChange;
	
	pc.addStream(local.stream);
}

function handleIceCandidate(event){
	console.log("ice candidate事件被触发: ",event);
	console.log(event.candidate);
	if(event.candidate){
		/*transferMsg(JSON.stringify(event.candidate));*/
		transferMsg(JSON.stringify({
			"type":"candidate",
			"label":event.candidate.sdpMLineIndex,
			"id":event.candidate.sdpMid,
			"candidate":event.candidate.candidate
		}));
	}else{
		console.log("End of candidates.");
	}
}

function handleRemoteStreamAdded(event){
	console.log("Added Remote Stream",event);
	/*vm.remoteVideo = window.URL.createObjectURL(event.stream);*/
	var test = window.URL.createObjectURL(event.stream);
	remoteVideoTest.push(test);
	remote.stream = event.stream;
}

function handleRemoteStreamRemoved(event) {
	  console.log('Remote stream removed. Event: ', event);
}

function onIceStateChange(event){
	console.log("Ice State has change: "+e)
}

function onSendChannelStateChange(){
	console.log("Send Channel State has change: "+dataChannel.readyState);
}

function doCall(){
	console.log("send offer to peer");
	pc.createOffer(setLocalAndSendMessage, handleCreateOfferError);
}

function doAnswer(){
	console.log("send answer to peer");
	pc.createAnswer().then(
		setLocalAndSendMessage,
		onCreateSessionDescriptionError
	);
}

function handleCreateOfferError(event){
	console.log("createOffer() error: ",event);
}

function setLocalAndSendMessage(sessionDescription) {
  // Set Opus as the preferred codec in SDP if Opus is present.
  //  sessionDescription.sdp = preferOpus(sessionDescription.sdp);
  pc.setLocalDescription(sessionDescription);
  console.log('setLocalAndSendMessage sending message', sessionDescription);
  /*sendMsg("/app/test/message",JSON.stringify(sessionDescription));*/
  transferMsg(JSON.stringify(sessionDescription));
}

function onCreateSessionDescriptionError(error) {
  console.log('Failed to create session description: ' + error.toString());
}

function receivehandler(event){
	receiveChannel = event.channel;
	receiveChannel.onopen = onReceiveChannelStateChange;
	receiveChannel.onclose = onReceiveChannelStateChange;
	receiveChannel.onmessage = onReceiveMessageCallback;
}

function onReceiveMessageCallback(event){
	vm.verbose.push(event.data);
}

function onReceiveChannelStateChange(){
	console.log("接受数据通道状态: "+ receiveChannel.readyState);
}

function closeWebRTC(){
	pc.close();
	pc = null;
	receiveChannel.close();
	receiveChannel = null;
	dataChannel.close();
	dataChannel = null;
}